<template>
  <SearchForm :options="formOptions" @search-refresh="getTableList"></SearchForm>
  <slot name="top"></slot>
  <view class="table">
    <view v-if="displayTableData.length">
      <view v-for="(item, index) in displayTableData" :key="index" class="item">
        <view class="left">
          <view class="tag" />
          <text class="m-l-5">
            {{ item.key }}
          </text>
          <view>
            <view v-if="singleCheckAll" class="f-center">
              <!-- 单条数据全选 -->
              <u-icon
                :name="!item.fold ? 'arrow-up' : 'arrow-down'"
                class="pr15"
                size="14px"
                :color="globalTheme.basicColor.primary"
                @tap="item.fold = !item.fold"
              />
              <view class="check-all">
                <u-checkbox-group
                  v-model="checkAllValue[index]"
                  :active-color="globalTheme.basicColor.primary"
                  @change="value => singleGroupChange(value, index)"
                >
                  <u-checkbox shape="circle" label="全选" name="全选" />
                </u-checkbox-group>
              </view>
            </view>
          </view>
        </view>
        <view class="right" v-show="item.fold">
          <view class="child">
            <!-- <u-transition :show="item.fold"> -->
            <view v-for="(child, cKey) in item.value" :key="cKey" v-waterMarker="useWaterMarkerParams">
              <view v-if="multiple" :class="isChecked(child.id)" />
              <view v-for="(head, hKey) in columns" :key="hKey" @tap="tableClick(child, item, index)">
                <view class="child-item" :class="hKey === columns.length - 1 && item.value.length > 1 ? 'border-bottom' : ''">
                  <!-- 特殊值 -->
                  <view v-if="specialField && hKey === 0" class="special-field">
                    {{ child[head.prop as any] }}
                  </view>

                  <!--标签  -->
                  <view v-else :class="hKey !== 0 ? 'label' : 'bold-label'" :style="labelStyle()">
                    {{ hKey !== 0 ? head.label : child[head.prop as any] }}
                  </view>

                  <!-- 值 -->
                  <view class="value" :style="valueStyle()">
                    {{ hKey === 0 ? "" : child[head.prop as any] || "--" }}
                  </view>

                  <!-- 操作按钮 -->
                  <view v-if="hKey === 0" class="child-btn">
                    <slot name="bottom" :item="child" :index="cKey"></slot>
                  </view>
                </view>
              </view>

              <view :class="cKey !== item.value.length - 1 ? 'bottom' : ''" />
            </view>
            <!-- </u-transition> -->
          </view>
          <!-- 主数据操作按钮 -->
          <slot name="allBtn" :item="item" :index="index"></slot>
        </view>
      </view>
    </view>
    <view v-else class="no-data"> 暂无数据 </view>
  </view>
</template>
<script setup lang="ts" name="ProTable">
import { useTable } from "./hooks/use-table";
import { useOther } from "./hooks/use-other";
import { ColumnProps } from "../ProTable/interface";
import { searchFromOptionsProp } from "../SearchForm/interface";

const globalTheme = useThemeStore();
export interface ProTable2Props {
  data?: any[]; // 自定义表格数据
  useData?: boolean; // 是否使用 props.data 内数据
  columns: ColumnProps[]; // 列配置项  ==> 必传
  requestApi?: (params: any) => Promise<any>; // 请求表格数据的 api ==> 非必传
  requestAuto?: boolean; // 是否自动执行请求 api ==> 非必传（默认为true）
  singleCheckAll?: boolean; // 单条主数据全选
  multiple?: boolean; // 是否可以多选
  specialField?: boolean; // 右上角显示的特殊字段
  initParam?: any; // 初始化请求参数 ==> 非必传（默认为{}）
  dataCallback?: (data: any) => any; // 返回数据的回调函数，可以对数据进行处理 ==> 非必传
  labelWidth?: number;
  waterMarkerParams?: string; // 水印的宽高

  // --查询表单相关
  formOptions?: searchFromOptionsProp[];
}

const $emit = defineEmits(["selectChange"]);
// 接受父组件参数，配置默认值
const props = withDefaults(defineProps<ProTable2Props>(), {
  columns: () => [],
  data: () => [],
  singleCheckAll: false,
  multiple: false,
  useData: false,
  labelWidth: 150
});

// 显示的表格数据
const displayTableData = computed(() => (props.useData ? props.data : tableData.value));

let useWaterMarkerParams = reactive({
  width: 0,
  height: 0
});

onBeforeMount(() => {
  init();
});

const init = () => {
  // 水印宽高处理
  if (props.waterMarkerParams) {
    const arr = props.waterMarkerParams.split(",");
    Object.assign(useWaterMarkerParams, {
      width: arr[0],
      height: arr[1]
    });
  }
};

// 选择后数据
const selectChange = (multipleSelection: any[]) => {
  $emit("selectChange", multipleSelection);
};

const {
  tableData,
  checkAllValue,
  multipleIds,
  multipleSelection,
  getTableList,
  isChecked,
  setMultipleSelection,
  singleGroupChange
} = useTable(props.initParam, props.singleCheckAll, selectChange, props.requestApi, props.dataCallback);
const { labelStyle, valueStyle } = useOther(props.labelWidth);

// 表格点击
const tableClick = (item, row, index) => {
  if (props.multiple) {
    // 多选
    setMultipleSelection(item, row, index);
    return;
  }
};
defineExpose({ getTableList, tableData, multipleIds, multipleSelection });
</script>
<style lang="scss" scoped src="./index.scss"></style>
